#include "add_st.h"
#include "ui_add_st.h"
#include<QSqlQuery>


add_st::add_st(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::add_st)
{
    ui->setupUi(this);
}

add_st::~add_st()
{
    delete ui;
}

//返回管理员操作界面
void add_st::on_exit_clicked()
{
    ui->line1->setText("");
    ui->line2->setText("");
    ui->box1->setCurrentIndex(0);
    ui->box2->setCurrentIndex(0);

    this->close();
}

//添加学生信息按钮
void add_st::on_add_clicked()
{
    QString id=ui->line1->text();
    QString name=ui->line2->text();
    QString sex=ui->box1->currentText();
    QString year=ui->box2->currentText();

    QSqlQuery query;

    query.prepare("select id from st where id=:id");
    query.bindValue(":id",id);
    query.exec();
    if(query.next())
        ui->tip->setText("学生已存在！");
    else{

        //向学生表中插入信息，密码默认123
        query.prepare("insert into st values(:id,:name,:sex,:year,:pwd)");

        QString pwd=QString::number(123);
        query.bindValue(":id",id);
        query.bindValue(":name",name);
        query.bindValue(":sex",sex);
        query.bindValue(":year",year);
        query.bindValue(":pwd",pwd);
        //判断是否插入成功
        if(query.exec()){

        //向成绩表中插入信息，各科成绩默认0
        query.prepare("insert into gpa(id) values(:id)");
        query.bindValue(":id",id);
        bool isAdd2=query.exec();

        if(isAdd2){
        qDebug()<<"add "<<id<<' '<<name<<' '
               <<sex<<' '<<year<<'\n';
        ui->tip->setText("添加学生成功!");

        }
        else{
            ui->tip->setText("添加失败!");
            //gpa表添加失败后将st表中学生记录删除，保持id一致性
            query.prepare("detele from st where id=:id");
            query.bindValue(":id",id);
            query.exec();
        }

        }
        else{
            ui->tip->setText("添加失败！");
        }
    }


}
